package com.example.myapplication;

import android.content.Context;
import android.net.Uri;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ui.PlayerView;
import com.example.myapplication.R;
import com.example.myapplication.Video;

public class VideoViewHolder extends RecyclerView.ViewHolder {

    private static final String TAG = "VideoViewHolder";
    public PlayerView playerView;
    public ExoPlayer player;
    private TextView videoTitle;
    private Context context;
    private GestureDetector gestureDetector;

    public VideoViewHolder(@NonNull View itemView) {
        super(itemView);
        context = itemView.getContext();
        playerView = itemView.findViewById(R.id.playerView);
        videoTitle = itemView.findViewById(R.id.videoTitle);
        Log.d(TAG, "VideoViewHolder: Initializing PlayerView and TextView");

        // Initialize ExoPlayer
        player = new ExoPlayer.Builder(context).build();
        playerView.setPlayer(player);
        Log.d(TAG, "VideoViewHolder: ExoPlayer initialized and set to PlayerView");

        // Set click listener for play/pause
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (player.isPlaying()) {
                    player.pause();
                    Log.d(TAG, "onSingleTapUp: Video paused");
                } else {
                    player.play();
                    Log.d(TAG, "onSingleTapUp: Video played");
                }
                return true;
            }
        });

        playerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
    }

    public void bind(Video video) {
        Log.d(TAG, "bind: Binding video with title: " + video.getTitle() + ", URL: " + video.getUrl());
        videoTitle.setText(video.getTitle());
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(video.getUrl()));
        player.setMediaItem(mediaItem);
        player.prepare();
    }

    public void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
            Log.d(TAG, "releasePlayer: ExoPlayer released");
        } else {
            Log.d(TAG, "releasePlayer: ExoPlayer is already null, no need to release");
        }
    }
}